/**
 * PromptSidebar - 提示词管理工具
 * Copyright (C) 2025
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 */

import type { Prompt, StorageData } from '@/types';

export default defineContentScript({
  matches: ['<all_urls>'],
  main() {
    // 双击 Ctrl 键相关变量
    let ctrlKeyCount = 0;
    let ctrlKeyTimer: NodeJS.Timeout | null = null;
    let settings: any = null;

    // 获取设置
    async function getSettings() {
      try {
        // 使用 WXT storage API 获取设置
        const settingsData = await storage.getItem<StorageData['settings']>('local:settings');
        settings = settingsData || { autoReplace: true, doubleCtrlDelay: 300 };
      } catch (error) {
        console.error('获取设置失败:', error);
        settings = { autoReplace: true, doubleCtrlDelay: 300 };
      }
    }

    // 初始化设置
    getSettings();

    // 监听设置变化 - 使用 WXT storage watch API
    const unwatchSettings = storage.watch<StorageData['settings']>('local:settings', (newValue, oldValue) => {
      if (newValue) {
        settings = newValue;
      }
    });

    // 监听键盘事件 - 双击 Ctrl 键
    document.addEventListener('keydown', async (event) => {
      if (!settings?.autoReplace) return;

      if (event.key === 'Control' || event.ctrlKey) {
        ctrlKeyCount++;
        
        if (ctrlKeyCount === 1) {
          // 第一次按下 Ctrl，启动计时器
          ctrlKeyTimer = setTimeout(() => {
            ctrlKeyCount = 0;
          }, settings.doubleCtrlDelay || 300);
        } else if (ctrlKeyCount === 2) {
          // 双击 Ctrl 键被触发
          if (ctrlKeyTimer) {
            clearTimeout(ctrlKeyTimer);
            ctrlKeyTimer = null;
          }
          ctrlKeyCount = 0;
          
          // 处理快捷短语替换
          await handleShortcutReplacement();
        }
      } else {
        // 按下其他键时重置计数
        ctrlKeyCount = 0;
        if (ctrlKeyTimer) {
          clearTimeout(ctrlKeyTimer);
          ctrlKeyTimer = null;
        }
      }
    });

    // 处理快捷短语替换
    async function handleShortcutReplacement() {
      const activeElement = document.activeElement as HTMLElement;
      
      if (!activeElement || !(
        activeElement.tagName === 'INPUT' || 
        activeElement.tagName === 'TEXTAREA' || 
        activeElement.contentEditable === 'true'
      )) {
        return;
      }

      let currentText = '';
      let selectionStart = 0;
      let selectionEnd = 0;

      // 获取当前文本和光标位置
      if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') {
        const inputElement = activeElement as HTMLInputElement | HTMLTextAreaElement;
        currentText = inputElement.value;
        selectionStart = inputElement.selectionStart || 0;
        selectionEnd = inputElement.selectionEnd || 0;
      } else if (activeElement.contentEditable === 'true') {
        currentText = activeElement.textContent || '';
        const selection = window.getSelection();
        if (selection && selection.rangeCount > 0) {
          const range = selection.getRangeAt(0);
          selectionStart = range.startOffset;
          selectionEnd = range.endOffset;
        }
      }

      // 查找光标前的快捷短语
      const textBeforeCursor = currentText.substring(0, selectionStart);
      const shortcutMatch = textBeforeCursor.match(/\/\w+$/);
      
      if (!shortcutMatch) {
        return;
      }

      const shortcut = shortcutMatch[0];
      const shortcutStartPos = selectionStart - shortcut.length;

      // 获取所有提示词
      try {
        // 使用 WXT storage API 获取提示词
        const prompts = await storage.getItem<Prompt[]>('local:prompts') || [];
        
        // 查找匹配的提示词
        const matchedPrompt = prompts.find((prompt: Prompt) => prompt.shortcut === shortcut);
        
        if (matchedPrompt) {
          // 直接替换，不处理变量
          replaceShortcut(shortcutStartPos, selectionStart, matchedPrompt.content);
        }
      } catch (error) {
        console.error('获取提示词失败:', error);
      }
    }

    // 替换快捷短语
    function replaceShortcut(startPos: number, endPos: number, replacementText: string) {
      const activeElement = document.activeElement as HTMLElement;
      
      if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') {
        const inputElement = activeElement as HTMLInputElement | HTMLTextAreaElement;
        const value = inputElement.value;
        
        inputElement.value = value.substring(0, startPos) + replacementText + value.substring(endPos);
        inputElement.selectionStart = inputElement.selectionEnd = startPos + replacementText.length;
        
        // 触发 input 事件
        inputElement.dispatchEvent(new Event('input', { bubbles: true }));
      } else if (activeElement.contentEditable === 'true') {
        const selection = window.getSelection();
        if (selection && selection.rangeCount > 0) {
          const range = document.createRange();
          const textNode = activeElement.firstChild;
          if (textNode) {
            range.setStart(textNode, startPos);
            range.setEnd(textNode, endPos);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
          }
        }
      }
    }

    // 监听来自 background script 的消息
    browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
      if (message.type === 'INSERT_TEXT') {
        insertTextToActiveElement(message.text);
        sendResponse({ success: true });
      } else if (message.type === 'REPLACE_TEXT') {
        // 处理变量填充后的文本替换
        const { startPos, endPos, text } = message.data;
        replaceShortcut(startPos, endPos, text);
        sendResponse({ success: true });
      }
      return true;
    });

    // 插入文本到当前活动元素
    function insertTextToActiveElement(text: string) {
      const activeElement = document.activeElement as HTMLElement;
      
      if (activeElement && (
        activeElement.tagName === 'INPUT' || 
        activeElement.tagName === 'TEXTAREA' || 
        activeElement.contentEditable === 'true'
      )) {
        if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') {
          const inputElement = activeElement as HTMLInputElement | HTMLTextAreaElement;
          const start = inputElement.selectionStart || 0;
          const end = inputElement.selectionEnd || 0;
          const value = inputElement.value;
          
          inputElement.value = value.substring(0, start) + text + value.substring(end);
          inputElement.selectionStart = inputElement.selectionEnd = start + text.length;
          
          // 触发 input 事件
          inputElement.dispatchEvent(new Event('input', { bubbles: true }));
        } else if (activeElement.contentEditable === 'true') {
          // 处理可编辑元素
          const selection = window.getSelection();
          if (selection && selection.rangeCount > 0) {
            // 创建粘贴事件
            const pasteEvent = new ClipboardEvent('paste', {
                clipboardData: new DataTransfer(),
                bubbles: true
            });
            // 设置剪贴板数据
            pasteEvent.clipboardData?.setData('text/plain', text);
            // 触发事件
            activeElement.dispatchEvent(pasteEvent);
          }
        }
      } else {
        // 如果没有活动的输入元素，尝试查找页面上的输入框
        const inputs = document.querySelectorAll('input[type="text"], input[type="search"], textarea, [contenteditable="true"]');
        if (inputs.length > 0) {
          const firstInput = inputs[0] as HTMLElement;
          firstInput.focus();
          
          // 递归调用以插入文本
          setTimeout(() => insertTextToActiveElement(text), 10);
        } else {
          // 复制到剪贴板作为备选方案
          navigator.clipboard.writeText(text).catch(() => {
            console.warn('无法插入文本或复制到剪贴板');
          });
        }
      }
    }

    console.log('提示词管理工具 Content Script 已加载');
  }
});
